package main

import (
	"fmt"
	"os"
	"sync"
	"time"

	"github.com/go-redis/redis/v8"
)

// LogProcessor 从消息队列中拉取日志并处理
func LogProcessor(client *redis.Client, queueName string, wg *sync.WaitGroup) {
	defer wg.Done()

	// 打开日志文件
	logFile, err := os.OpenFile("log_output.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Printf("Failed to open log file: %v\n", err)
		return
	}
	defer logFile.Close()

	for {
		messages, err := PullMessages(client, queueName, 5)
		if err != nil {
			fmt.Printf("Failed to pull log messages: %v\n", err)
			time.Sleep(1 * time.Second)
			continue
		}

		if len(messages) == 0 {
			time.Sleep(1 * time.Second)
			continue
		}

		// 处理拉取到的日志消息
		for _, message := range messages {
			_, err := logFile.WriteString(message + "\n")
			if err != nil {
				fmt.Printf("Failed to write log message to file: %v\n", err)
			}
		}

		// 确认消息已处理
		AckMessages(client, queueName, int64(len(messages)))
	}
}
